package org.zb.shiro.controller;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zb.shiro.form.UserForm;
import org.zb.shiro.form.UserForm.CreateUser;
import org.zb.shiro.form.UserForm.EditUser;
import org.zb.security.auth.BCryptPasswordEncoder;
import org.zb.shiro.model.User;
import org.zb.shiro.service.UserService;
import org.zb.web.response.AjaxResult;

import com.github.pagehelper.Page;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/add")
	public String add(UserForm userForm){
		return "user/add";
	}
	
	@PostMapping("/add")
	@ResponseBody()
	public AjaxResult add(@Validated(CreateUser.class) UserForm userForm, BindingResult result) {
		AjaxResult rst = new AjaxResult();
		if(result.hasErrors()) {
			rst.setCode("error");
			rst.setValidatedResult(result);
			return rst;
		} 
		
		User user = new User();
		user.setUsername(userForm.getUsername());
		user.setEmail(userForm.getEmail());
		user.setCreateTime(new Date());
		user.setStatus(0);
		if(userForm.getPassword()!=null) {
			user.setPassword(new BCryptPasswordEncoder().encode(userForm.getPassword()));
		}
		
		if(userService.saveUser(user) > 0) {
			
			rst.setCode("success");
			rst.setMessage("添加成功");
		} else {
			
			rst.setCode("error");
			rst.setMessage("服务器错误");
		}
		
		return rst;
	}
	
	@GetMapping("/edit/{id}")
	public String edit( UserForm userForm,@PathVariable(name="id") Long id){
		User user = userService.findById(id);
		userForm.setUsername(user.getUsername());
		userForm.setEmail(user.getEmail());
		return "user/edit";
	}
	
	@PostMapping("/edit/{id}")
	@ResponseBody()
	public AjaxResult edit(@PathVariable(name="id") Long id,@Validated(EditUser.class) UserForm userForm, BindingResult result) {
		AjaxResult rst = new AjaxResult();
		if(result.hasErrors()) {
			rst.setCode("error");
			rst.setValidatedResult(result);
			return rst;
		} 
		User user = userService.findById(id);
		if (user != null) {
			user.setUsername(userForm.getUsername());
			user.setEmail(userForm.getEmail());
			if (userForm.getPassword() != null) {
				user.setPassword(new BCryptPasswordEncoder().encode(userForm.getPassword()));
			}
			if(userService.updateUser(user) > 0) {
				
				rst.setCode("success");
				rst.setMessage("更新成功");
			} else {
				
				rst.setCode("error");
				rst.setMessage("服务器错误");
			}
		} else {
			rst.setCode("error");
			rst.setMessage("用户不存在");
		}
		return rst;
	}
	
	@PostMapping("/status")
	@ResponseBody
	public int changeStatus(@RequestParam Long id, @RequestParam Integer status)
	{
		User user = new User();
		user.setId(id);
		user.setStatus(status);
		return userService.updateUser(user);
	}
	
	
	@PostMapping("/delete")
	@ResponseBody
	public int delete(@RequestParam Long id)
	{
		User user = userService.findById(id);
		return userService.deleteUser(user);
	}
	
	@PostMapping("/patch-delete")
	@ResponseBody
	public int patchDelete(@RequestParam(name="ids[]") Long[] ids)
	{
		if(ids !=null) {
			return userService.patchDeleteByIds(ids);
		}
		return 0;
	}
	
	@GetMapping("/list")
	public String list(ModelMap model,@RequestParam Map<String, Object> params){
		Page<User> users = (Page<User>) userService.searchAll(params);
		model.addAttribute("params",params);
		model.addAttribute("users",users);
		model.addAttribute("totalRecords",users.getTotal());
		model.addAttribute("totalPages",users.getPages());
		model.addAttribute("pageNum",users.getPageNum());
		return "user/list";
	}
}
